package com.arvato.admin01.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.arvato.admin01.orm.StudentMapper;
import com.arvato.admin01.pojo.DataResult;
import com.arvato.admin01.pojo.ExportYqfkdj;
import com.arvato.admin01.pojo.Student;
import com.arvato.admin01.service.CacheLoader;
import com.arvato.admin01.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author xu yuanjun
 * @data 2020/3/29 17:22
 */
@Service
@Slf4j
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     *代码封装引入缓存方法
     */
    @Autowired
    private CacheTemplateService cacheTemplateService;

    public List<Student> query(){
        String key = "studentCache";
        String json = redisTemplate.opsForValue().get(key);
        if (json==null||"".equals(json)||"null".equalsIgnoreCase(json)){
           synchronized (this){
               json = redisTemplate.opsForValue().get(key);
               if (json!=null||!"".equals(json)||!"null".equalsIgnoreCase(json)){
                   JSON.parseArray(json,Student.class);
               }
            List<Student> studentList = studentMapper.query();
               //加入缓存 设置缓存时间
            redisTemplate.opsForValue().set(key, JSON.toJSONString(studentList), 60, TimeUnit.SECONDS);
            return studentList;
        }
       }
        return JSON.parseArray(json,Student.class);
    }


    // 代码抽象
    // 对数组进行缓存
    @Override
    public List<Student> queryNew(){
        String key = "studentCache";
        List<Student> data = cacheTemplateService.findData(key, 60, new TypeReference<List<Student>>() {
        }, new CacheLoader<List<Student>>() {
            @Override
            public List<Student> load() {
                return studentMapper.query();
            }
        });
        return data;
    }

    // 代码抽象
    // 对对象进行缓存
    @Override
    public Student queryObject(){
        String key = "studentCache";
        Student data = cacheTemplateService.findData(key, 60, new TypeReference<Student>() {
        }, new CacheLoader<Student>() {
            @Override
            public Student load() {
                return studentMapper.queryObject();
            }
        });
        return data;
    }

    // 代码抽象
    // 对字符串 进行缓存
    @Override
    public String queryString(){
        String key = "studentCache";
        String data = cacheTemplateService.findData(key, 60, new TypeReference<String>() {
        }, new CacheLoader<String>() {
            @Override
            public String load() {
                return studentMapper.queryString();
            }
        });
        return data;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertData(String name, String email) throws Exception {
        synchronized(this){
            String cache = this.getRegCache(name, email);
            if (!ObjectUtils.isEmpty(cache)){
                throw new Exception("用户重复注册");
            } else {
                this.generateRegCache(name,email);
            }
        }
        studentMapper.insert(name, email);
    }


    /**
     *	 根据name 和 邮箱进行 缓存验证
     * @param
     * @return
     */
    public  void generateRegCache(String name, String email) {
        if(redisTemplate.opsForValue().setIfAbsent(email.trim()+name.trim(), "")) {
            redisTemplate.opsForValue().set(email.trim()+name.trim(), "1", 30, TimeUnit.SECONDS);
        }
    }

    /**
     * 	获取name 和 邮箱进行 缓存验证 缓存
     * @param
     * @return
     */
    public String getRegCache(String name, String email) {
        return redisTemplate.opsForValue().get(email.trim()+name.trim());
    }

    /**
     * 导出
     * @param yqfkdjBean
     * @author zhouhong
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = { Exception.class })
    public DataResult exporYqfkdj(ExportYqfkdj yqfkdjBean) throws Exception {
        DataResult result = new DataResult();



        List<ExportYqfkdj> list = new ArrayList<ExportYqfkdj>();
        try {
            /* 查询导出信息 */
            //result = getYqfkMhCXQuery(yqfkdjBean);
            ExportYqfkdj exportYqfkdj =new ExportYqfkdj();
            exportYqfkdj.setDqjkzt("123");
            ExportYqfkdj exportYqfkdj1 =new ExportYqfkdj();
            exportYqfkdj1.setDqjkzt("456");
            ExportYqfkdj exportYqfkdj2 =new ExportYqfkdj();
            exportYqfkdj2.setDqjkzt("789");
            List<ExportYqfkdj> data = new ArrayList<>();
            data.add(exportYqfkdj);
            data.add(exportYqfkdj1);
            data.add(exportYqfkdj2);
            result.setResults(data);
            result.setTotalcount(data.size());


            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmssSSS");
            for (int i = 0; i < result.getTotalcount(); i++) {
                ExportYqfkdj dmKhfwdcDtjlZxDto = new ExportYqfkdj();
                dmKhfwdcDtjlZxDto = result.getResults().get(i);
                dmKhfwdcDtjlZxDto.setXuhao(i + 1);
                list.add(dmKhfwdcDtjlZxDto);
            }
            String filepath = "D:/疫情防控信息" + df.format(new Date()) + ".xlsx";
            if (System.getProperty("os.name").toLowerCase().startsWith("li")
                    || System.getProperty("os.name").toLowerCase().startsWith("lin")) {
                filepath = "/home/Tomcat/temp/" + df.format(new Date()) + ".xlsx";
            }
            EasyExcel.write(filepath, ExportYqfkdj.class).head(head()).sheet().doWrite(list);
            result.setResults(list);
            result.setSuccess(true);
            result.setMsg(filepath);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("查询失败");
            e.printStackTrace();
            throw e;
        }
        return result;
    }


    /**
     * 疫情防控信息导出表头
     * @author zhouhong
     * @return List<List<String>>
     */
    private List<List<String>> head() {
        List<List<String>> list = new ArrayList<List<String>>();
        List<String> head0 = new ArrayList<String>();
        head0.add("序号");
        List<String> head1 = new ArrayList<String>();
        head1.add("姓名");
        List<String> head2 = new ArrayList<String>();
        head2.add("证件号码");
        List<String> head3 = new ArrayList<String>();
        head3.add("联系电话");
        List<String> head4 = new ArrayList<String>();
        head4.add("工作所在单位");
        List<String> head5 = new ArrayList<String>();
        head5.add("是否接触疑似病例");
        List<String> head6 = new ArrayList<String>();
        head6.add("是否与隔离人员同住");
        List<String> head7 = new ArrayList<String>();
        head7.add("当前状态");
        List<String> head8 = new ArrayList<String>();
        head8.add("当前健康状态");
        List<String> head9 = new ArrayList<String>();
        head9.add("体温(°C)");
        List<String> head10 = new ArrayList<String>();
        head10.add("当前所在地址");
        List<String> head11 = new ArrayList<String>();
        head11.add("当前居住地址");
        List<String> head12 = new ArrayList<String>();
        head12.add("提交时间");
        list.add(head0);
        list.add(head1);
        list.add(head2);
        list.add(head3);
        list.add(head4);
        list.add(head5);
        list.add(head6);
        list.add(head7);
        list.add(head8);
        list.add(head9);
        list.add(head10);
        list.add(head11);
        list.add(head12);
        return list;
    }

}
